package com.pb.wkflow.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.pb.wkflow.api.controller.assembler.WfSysProcInfoAssembler;
import com.pb.wkflow.api.controller.request.ProcessInstanceCreateRequest;
import com.pb.wkflow.api.entity.WfSysProcInfoEntity;
import com.pb.wkflow.api.mapper.WfSysProcInfoMapper;
import com.pb.wkflow.api.service.WfSysProcInfoService;
import com.pb.wkflow.core.config.Constants;
import com.pb.wkflow.core.utils.DateUtils;
import org.camunda.bpm.engine.repository.ProcessDefinition;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * @author 苗益辉
 * @date 2022/9/28 10:24
 */
@Service
public class WfSysProcInfoServiceImpl implements WfSysProcInfoService {

    @Autowired
    WfSysProcInfoMapper wfSysProcInfoMapper;

    /**
     * 新增流程信息表
     * @param processDefinition 流程定义
     * @param processInstance 流程实例
     * @param request 其他信息
     */
    @Override
    public void insert(ProcessDefinition processDefinition,
                       ProcessInstance processInstance, ProcessInstanceCreateRequest request) {
        WfSysProcInfoEntity wfSysProcInfoEntity = WfSysProcInfoAssembler.assemblerToInsert(processDefinition,
                processInstance, request);
        wfSysProcInfoMapper.insert(wfSysProcInfoEntity);
    }

    /**
     * 更新流程状态
     * @param processInstanceId 流程定义id
     * @param processStatus 流程状态
     */
    @Override
    public void update(String processInstanceId, String processStatus, Map<String, Object> paramsMap, String isEnd) {
        WfSysProcInfoEntity.WfSysProcInfoEntityBuilder wfSysProcInfoEntityBuilder = WfSysProcInfoEntity.builder();
        wfSysProcInfoEntityBuilder.procInstId(processInstanceId).processStatus(processStatus);
        if (paramsMap != null && paramsMap.containsKey(Constants.EXTENSION_DATA)) {
            wfSysProcInfoEntityBuilder.paramMap(JSON.toJSONString(paramsMap));
        }
        if (Constants.Flag.TRUE.equals(isEnd)) {
            wfSysProcInfoEntityBuilder.endTime(DateUtils.dateToStr(new Date()));
        }
        wfSysProcInfoMapper.update(wfSysProcInfoEntityBuilder.build());
    }

    /**
     * 根据流程实例id删除
     * @param processInstanceId 流程实例id
     */
    @Override
    public void delete(String processInstanceId) {
        wfSysProcInfoMapper.deleteByProcessInstId(processInstanceId);
    }

    /**
     * 根据流程实例id查询
     * @param processInstanceId 流程实例id
     * @return WfSysProcInfoEntity
     */
    @Override
    public WfSysProcInfoEntity selectOne(String processInstanceId) {
        return wfSysProcInfoMapper.selectOne(processInstanceId);
    }
}
